from rest_framework import serializers
from .models import Course, CourseSubscription


class CourseSerializer(serializers.ModelSerializer):
    is_subscribed = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = '__all__'

    def get_is_subscribed(self, obj):
        user = self.context['request'].user
        if not user.is_authenticated:
            return False

        return CourseSubscription.objects.filter(
            user=user,
            course=obj,
            is_active=True
        ).exists()


class CourseSubscriptionSerializer(serializers.ModelSerializer):
    course_title = serializers.CharField(source='course.title', read_only=True)
    course_cover = serializers.CharField(source='course.cover_url', read_only=True)

    class Meta:
        model = CourseSubscription
        fields = ('id', 'course', 'course_title', 'course_cover', 'subscribed_at', 'is_active')